<!-- ❗Errors in the form are set on line 60 -->
<script setup>
import { useGenerateImageVariant } from "@core/composable/useGenerateImageVariant";
import authV2LoginIllustrationDark from "@images/loginImage.png";
import authV2LoginIllustrationBorderedDark from "@images/pages/auth-v2-login-illustration-bordered-dark.png";
import authV2LoginIllustrationBorderedLight from "@images/pages/auth-v2-login-illustration-bordered-light.png";
import { VForm } from "vuetify/components/VForm";
// import authV2LoginIllustrationLight from '@images/pages/auth-v2-login-illustration-light.png'
import { to } from "await-to-js";
import { useUserStore } from "@/store/modules/user";
import authV2LoginIllustrationLight from "@images/loginImage.png";
import authV2MaskDark from "@images/pages/misc-mask-dark.png";
import authV2MaskLight from "@images/pages/misc-mask-light.png";
import { VNodeRenderer } from "@layouts/components/VNodeRenderer";
import { themeConfig } from "@themeConfig";
import { sendHeartbeat } from '@/api/singlePoint';

import AuthProvider from '@/views/pages/authentication/AuthProvider.vue';
import authV1BottomShape from '@images/svg/auth-v1-bottom-shape.svg?raw';
import authV1TopShape from '@images/svg/auth-v1-top-shape.svg?raw';

import beijin from "@images/beijin.png";

const router = useRouter();
const userStore = useUserStore();
const redirect = ref(undefined);

watch(
  () => router.currentRoute.value,
  (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
  },
  { immediate: true }
);
const authThemeImg = useGenerateImageVariant(
  authV2LoginIllustrationLight,
  authV2LoginIllustrationDark,
  authV2LoginIllustrationBorderedLight,
  authV2LoginIllustrationBorderedDark,
  true
);
const authThemeMask = useGenerateImageVariant(authV2MaskLight, authV2MaskDark);

definePage({
  meta: {
    layout: "blank",
    unauthenticatedOnly: true,
  },
});

const isPasswordVisible = ref(false);

const ability = useAbility();
const loading = ref(false);

const errors = ref({
  username: undefined,
  password: undefined,
});

const refVForm = ref();

const credentials = ref({
  tenantId: "000000",
  username: "",
  password: "",
  rememberMe: false,
  clientId: "e5cd7e4891bf95d1d19206ce24a7b32e",
  grantType: "password",
});

// const rememberMe = ref(false);

const getLoginData = () => {
  const tenantId = localStorage.getItem("tenantId");
  const username = localStorage.getItem("username");
  const password = localStorage.getItem("password");
  const rememberMe = localStorage.getItem("rememberMe");
  credentials.value = {
    tenantId: tenantId === null ? String(credentials.value.tenantId) : tenantId,
    username: username === null ? String(credentials.value.username) : username,
    password:
      password === null ? String(credentials.value.password) : String(password),
    rememberMe: rememberMe === null ? false : Boolean(rememberMe),
    clientId: "e5cd7e4891bf95d1d19206ce24a7b32e",
    grantType: "password",
  };
};
const login = async () => {
  localStorage.setItem("username", String(credentials.value.username));

  // 调用登录方法
  const [err] = await to(userStore.login(credentials.value));
  userStore.heartbeatInterval = setInterval(sendHeartbeat, 180000);
  if (!err) {
    const redirectUrl = redirect.value || "/";
    const userAbilityRules = [
      {
        action: "manage",
        subject: "all",
      },
    ];
    useCookie("userAbilityRules").value = userAbilityRules;
    ability.update(userAbilityRules);
    useCookie("userData").value = {
      id: 1,
      fullName: "John Doe",
      username: "johndoe",
      avatar: "/images/avatars/avatar-1.png",
      email: "admin@demo.com",
      role: "admin",
    };
    useCookie("accessToken").value =
      "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6Mn0.cat2xMrZLn0FwicdGtZNzL7ifDTAKWB0k1RurSWjdnw";
    await nextTick(() => {
      router.replace(redirectUrl);
    });
    loading.value = false;
  } else {
    loading.value = false;
  }
};

const onSubmit = () => {
  refVForm.value?.validate().then(({ valid: isValid }) => {
    // 勾选了需要记住密码设置在 localStorage 中设置记住用户名和密码
    if (credentials.value.rememberMe) {
      localStorage.setItem("tenantId", String(credentials.value.tenantId));
      localStorage.setItem("username", String(credentials.value.username));
      localStorage.setItem("password", String(credentials.value.password));
      localStorage.setItem("rememberMe", String(credentials.value.rememberMe));
    } else {
      // 否则移除
      localStorage.removeItem("tenantId");
      localStorage.removeItem("username");
      localStorage.removeItem("password");
      localStorage.removeItem("rememberMe");
    }
    if (isValid) login();
  });
};
onMounted(() => {
  getLoginData();
});
</script>

<template>
  <div class="auth-wrapper d-flex align-center justify-center pa-4" :style="'background-image: url('+beijin+');'">
    <div class="position-relative my-sm-16">
      <!-- 馃憠 Top shape -->
      <VNodeRenderer
        :nodes="h('div', { innerHTML: authV1TopShape })"
        class="text-primary auth-v1-top-shape d-none d-sm-block"
      />

      <!-- 馃憠 Bottom shape -->
      <VNodeRenderer
        :nodes="h('div', { innerHTML: authV1BottomShape })"
        class="text-primary auth-v1-bottom-shape d-none d-sm-block"
      />

      <!-- 馃憠 Auth Card -->
      <VCard
        class="auth-card"
        max-width="460"
        :class="$vuetify.display.smAndUp ? 'pa-6' : 'pa-0'"
      >
        <VCardItem class="justify-center">
          <VCardTitle>
            <RouterLink to="/">
              <div class="app-logo">
                <VNodeRenderer :nodes="themeConfig.app.logo" />
                <h1 class="app-logo-title">
                  {{ themeConfig.app.title }}
                </h1>
              </div>
            </RouterLink>
          </VCardTitle>
        </VCardItem>

        <VCardText>
          <h4 class="text-h4 mb-1">
           欢迎登入<span class="text-capitalize">{{ themeConfig.app.title }}</span>
          </h4>
          <p class="mb-0">
            {{ themeConfig.app.logo_title3 }}
          </p>
        </VCardText>

        <VCardText>
          <VForm ref="refVForm" @submit.prevent="onSubmit">
            <VRow>
              <!-- username -->
              <VCol cols="12">
                <AppTextField
                  v-model="credentials.username"
                  :label="themeConfig.app.logo_title5"
                  :placeholder="
                    themeConfig.app.logo_title7 + themeConfig.app.logo_title5
                  "
                  type="username"
                  autofocus
                  :rules="[requiredValidator]"
                  :error-messages="errors.username"
                />
              </VCol>
            
              <!-- password -->
              <VCol cols="12">
                <AppTextField
                  v-model="credentials.password"
                  :label="themeConfig.app.logo_title6"
                  :placeholder="
                    themeConfig.app.logo_title7 + themeConfig.app.logo_title6
                  "
                  :rules="[requiredValidator]"
                  :type="isPasswordVisible ? 'text' : 'password'"
                  :error-messages="errors.password"
                  :append-inner-icon="
                    isPasswordVisible ? 'tabler-eye-off' : 'tabler-eye'
                  "
                  @click:append-inner="isPasswordVisible = !isPasswordVisible"
                />
            
                <div
                  class="d-flex align-center flex-wrap justify-space-between my-6"
                >
                  <VCheckbox
                    v-model="credentials.rememberMe"
                    :label="themeConfig.app.logo_title8"
                    @click:append="
                      credentials.rememberMe = !credentials.rememberMe
                    "
                  />
            
                  <!-- <RouterLink class="text-primary ms-2 mb-1" :to="{ name: 'forgot-password' }" >
                    Forgot Password?
                  </RouterLink> -->
                </div>
            
                <VBtn block type="submit">
                  {{ themeConfig.app.logo_title9 }}
                </VBtn>
              </VCol>
            
              <!-- create account -->
              <VCol cols="12" class="text-center">
                <span>{{ themeConfig.app.logo_title10 }}</span>
              </VCol>
            </VRow>
          </VForm>
        </VCardText>
      </VCard>
    </div>
  </div>
</template>

<style lang="scss">
@use "@core/scss/template/pages/page-auth";

#LoginTitle {
  margin: 1.5rem;
}

/* 隐藏全局滚动条 */
::-webkit-scrollbar {
  width: 0; /* 宽度设为0 */
  height: 0; /* 高度设为0 */
}

/* 兼容 Firefox */
html {
  scrollbar-width: none; /* 隐藏滚动条 */
}

/* 兼容 IE/Edge */
html {
  -ms-overflow-style: none; /* 隐藏滚动条 */
}
</style>
